<?php
function checkNickname($dbc, $name){

	$query = "SELECT nickname FROM Players WHERE nickname = '$name'";
	$r = mysqli_query($dbc,$query);
	if(mysqli_num_rows($r) == 0){
		return TRUE;
	}
	else{
		return FALSE;
	}
}

function checkEmail($dbc, $email){

	$query = "SELECT email FROM Players WHERE email = '$email'";
	$r = mysqli_query($dbc,$query);
	if(mysqli_num_rows($r) == 0){
		return TRUE;
	}
	else{
		return FALSE;
	}
}

function validEmail($email){

	$pattern = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/'; 

	if(preg_match($pattern, $email)){
		return TRUE;
	}
	else{
		return FALSE;
	}
}

function registerUser($dbc, $nm, $e, $pw){

	$query = "INSERT INTO Players VALUES (NULL ,'$nm','$e',sha1('$pw'), 300)";
	$r = mysqli_query($dbc,$query);

	if($r){
		return TRUE;
	}
	else{
		return FALSE;
	}
}

function sendEmail($e, $nm, $pw){

	include ("utilities/class.phpmailer.php");
 
	$mail = new PHPMailer();
 
	$mail->IsSMTP();
	$mail->Host     = "mail.live.com";
	$mail->Port     = 465;
	$mail->SMTPAuth = true;
	$mail->SMTPSecure = 'ssl';
 
	$mail->Username = "insomnia_q3@hotmail.com";
	$mail->Password = "irinafurakourni4";
 
	$mail->From     = "admin@21game.com";
	$mail->FromName = "Webmaster 21Game";
 
	$mail->Subject  = "Welcome to 21Game!.";
	$mail->WordWrap = 50;
 
	//$mail->AddAttachment("/path/to/file.zip");                // archivo adjunto
	//$mail->AddAttachment("/path/to/image.jpg", "image2.jpg"); // archivo adjunto
 
	$mail->AddAddress("$e");                 // Correo destino
	$mail->IsHTML(TRUE);
 
	$mail->Body = "Your account have been created successfully. Your information is:<br><br>
	Nickname: ".$nm."<br>
	Email: ".$e."<br>
	Password: ".$pw."<br><br>	

	Thanks for joining our community.";

	$mail->Send();
 
	/*if(!$mail->Send()) {
    	echo "Error: " . $mail->ErrorInfo;
	} else {
    	echo "Mensaje enviado";
	}*/
}

function loginUser($dbc, $e, $pw){

	$query = "SELECT nickname ,password FROM Players WHERE email = '$e'";
	$r = mysqli_query($dbc,$query);
	$data = mysqli_fetch_array($r,MYSQLI_ASSOC);

	if(sha1($pw) == $data['password']){
		$_SESSION['username'] = $data['nickname'];
		return TRUE;
	}
	else{
		return FALSE;
	}
}

function challengePlayer($dbc, $oponent,$coins,$nickname){
	//Getting the oponent id
	$oponent_id = getPlayerId($dbc, $oponent);

	//Getting the amount of coins your opponent and you have.
	 $data = getCoins($dbc, $oponent,$nickname);
	 $oponentCoins = $data['0'];
	 $yourCoins = $data['1'];

	//Check if the bet is a number
	if(!is_numeric($coins) OR $coins == 0){
		echo "Your bet is not valid";
	}
	elseif($coins > $yourCoins){
		echo "You can't bet more than your have.";
	}
	elseif($coins > $oponentCoins){
		echo "You can't bet more than your oponent have.";
	}
	else{
		$playerid = getPlayerId($dbc, $_SESSION['username']);

		$query = "INSERT INTO Games VALUES (NULL, '$playerid', '$nickname', '$oponent', NULL, 'Pending', NULL, NULL, '$coins')";
		$r = mysqli_query($dbc,$query);

		$query = "UPDATE Players SET Coins = Coins - '$coins' WHERE player_id = '$playerid'";
		$r = mysqli_query($dbc,$query);

		//Send notification to the oponent
		$title = "$nickname has challenged you";
		$body = "$nickname has challenged you. If you want to accept his challenge you will have to pay $coins coins to play.
		To accept the match go to Your games in your profile menu.";

		sendNotification($dbc,$oponent_id, $title, $body);

		echo "<p class='lead'>You challenged $oponent. <b>$coins</b> coins has been substracted from your account since you win the challenge.<br>You can also cancel the challenge if your oponent does not accept or reject the challenge to recover your coins.";
		header( "Refresh:2; url=challenge.php" );
	}
}

function getCoins($dbc, $oponent, $you){

	$query = "SELECT coins FROM Players WHERE nickname = '$oponent'";
	$r = mysqli_query($dbc, $query);
	$data = mysqli_fetch_array($r, MYSQLI_ASSOC);
	
	$oponentCoins = $data['coins'];

	$query = "SELECT coins FROM Players WHERE nickname = '$you'";
	$r = mysqli_query($dbc, $query);
	$data = mysqli_fetch_array($r, MYSQLI_ASSOC);

	$yourCoins = $data['coins'];

	$data = "$oponentCoins,$yourCoins";

	$data = explode(",", $data);

	return $data;
}

function getPlayerId($dbc, $nickname){
	$query = "SELECT player_id FROM Players WHERE nickname = '$nickname'";
	$r = mysqli_query($dbc, $query);
	$data = mysqli_fetch_array($r, MYSQLI_ASSOC);

	return $data['player_id'];
}

function checkMatch($dbc, $you, $oponent){

	$query = "SELECT game_id FROM Games WHERE player1 = '$you' AND player2 = '$oponent' AND status != 'Finished'";
	$r = mysqli_query($dbc, $query);

	if(mysqli_num_rows($r) >= 1){
		return true;
	}
	else{
		return false;
	}
}

function sendNotification($dbc, $oponent, $title, $body){

	$query = "INSERT INTO Notifications VALUES (NULL, '$oponent', '$title', '$body', NOW(), '0')";
	$r = mysqli_query($dbc,$query);
}

function yourGames($dbc, $username){

	$query = "SELECT game_id, player1, player2,player_id, bet, status FROM Games WHERE player1 = '$username' OR player2 = '$username'";
	$r = mysqli_query($dbc, $query);

	if(mysqli_num_rows($r) == 0){
		echo "You actually have no games or challenges.";
	}
	else if($r){
		return $r;
	}
	else{
		echo "Something went wrong...";
	}
}

function markAsRead($dbc, $id){

	$query = "UPDATE Notifications SET seen = '1' WHERE notification_id = $id";
	$r = mysqli_query($dbc,$query);

	header("Location: notifications.php");
}

function cancelChallenge($dbc, $gameid, $playerid){

	//Getting back the coins
	$query = "SELECT bet, player1, player2, player_id FROM Games WHERE game_id = '$gameid'";
	$r = mysqli_query($dbc, $query);
	$row = mysqli_fetch_array($r, MYSQLI_ASSOC);

	if($row['player_id'] == $playerid){
		$p1 = $row['player1'];
		$p2 = $row['player2'];
	}
	else{
		$p1 = $row['player2'];
		$p2 = $row['player1'];
	}

	$playerid = $row['player_id'];
	$bet = $row['bet'];

	$query = "DELETE FROM Games WHERE game_id ='$gameid'";
	$r = mysqli_query($dbc, $query);

	if(mysqli_affected_rows($dbc) == 1){

		retrieveCoins($dbc, $gameid, $playerid, $bet);

		$title = "Canceled challenge";
		$body = "$p1 has cancelled the challenge";

		$p2 = getPlayerId($dbc, $p2);
		sendNotification($dbc, $p2, $title, $body);
		header("Location: yourgames.php");
	}
	else{
		echo "Something went wrong when cancelling the game";
	}
}

function retrieveCoins($dbc, $gameid, $playerid, $bet){

	$query = "UPDATE Players SET coins = coins + $bet WHERE player_id = '$playerid'";
	$r = mysqli_query($dbc, $query);

	if($r){
		$title = "Recovered coins";
		$body = "You have recovered <b>$bet</b> coins due to cancelling the Game <b>#$gameid</b>.";
		sendNotification($dbc, $playerid, $title, $body);
	}
	else{
		echo "Something went wrong recovering your coins.";
	}
}
 ?>